package com.ezerg.boot.shirojwt;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.ezerg.boot.shiro.bean.UserBean;
import com.ezerg.boot.shiro.service.UserService;
import com.ezerg.boot.shirojwt.util.JWTUtil;

//@Component
public class JWTRealm extends AuthorizingRealm {
	@Resource
    private UserService userService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	// 获取用户角色和权限
        String username = JWTUtil.getUsername(principals.toString());
        System.out.println("授权用户 [username]=" + username);
        UserBean user = userService.getUser(username);
        //
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        System.out.println("角色=" + user.getRole());
        simpleAuthorizationInfo.addRole(user.getRole());
        //
        System.out.println("权限=" + user.getPermission());
        Set<String> permission = new HashSet<String>(Arrays.asList(user.getPermission().split(",")));
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getPrincipal();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        System.out.println("认证用户 [username]=" + username);
        if (username == null) {
            throw new AuthenticationException("token invalid");
        }
        UserBean userBean = userService.getUser(username);
        if (userBean == null) {
            throw new AuthenticationException("User didn't existed!");
        }
        if (!JWTUtil.verify(token, username, userBean.getPassword())) {
            throw new AuthenticationException("User's password error");
        }
        return new SimpleAuthenticationInfo(token, token, username);
    }
}
